import {Store} from "koa-session2";
import redisShare from './redis.js';

export default class RedisStore extends Store {
  constructor() {
    super();
    this.redis = redisShare;
  }

  async get(sid) {
    // console.log(`get: SESSION:${sid}`)
    const session = await this.redis.get(`SESSION:${sid}`);
    if (session) return JSON.parse(session);
    return {};
  }

  async set(session, opts) {
    if(!opts.sid) {
      opts.sid = this.getID(24);
    }
    // console.log(`set: SESSION:${opts.sid}`)
    await this.redis.set(`SESSION:${opts.sid}`, JSON.stringify(session));
    this.redis.expire(`SESSION:${opts.sid}`, 86400);
    return opts.sid;
  }

  async destory(sid) {
    return await this.redis.del(sid);
  }
}